<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/5/31
 * Time: 15:20
 */

namespace app\api\controller\android\v13;


use app\api\model\MyOrderAward;
use app\api\model\MyOrderWithdrawal;
use think\Controller;
use app\api\model\Authority;
use think\Exception;
use  app\api\model\OrderModel;


class MyReward extends Controller
{
    protected $us;

    public function _initialize()
    {
        $this->us = Authority::check(1);

    }

    public function index(MyOrderAward $myOrderAward, \app\api\model\Common $common,OrderModel $orderModel)
    {

        $data            = Authority::param(['stareTime', 'state']);
        $data['user_id'] = $this->us['user_id'];
        if($this->us['quit_jobs']==1){
            r_date(null, 300,'代管或离职帐号无法提现');
        }
        $list            = $myOrderAward->list($data);
        foreach ($list as $k=>$l) {

            if($l['commission']==0 && $l['deal']!=0){
                $list[$k]['transactionType']="成交提成";
            }
            if($l['commission']!=0 && $l['deal']==0){
                $list[$k]['transactionType']="上门提成";
            }

        }
        $sum=$myOrderAward->sum($data);
        r_date(['data' => $list, 'sum' =>  empty($sum['sum'])?0:$sum['sum'], 'alreadySum' =>  empty($sum['alreadySum'])?0:$sum['alreadySum'], 'code' => $myOrderAward->creatToken($this->us['user_id']), 'binding' => empty($this->us['openid']) ? 0 : 1], 200);
    }

    /**
     * 提现创建定案
     * invoice_type
     */
    private function ding($data)
    {
        $myOrderWithdrawal = new MyOrderWithdrawal();

        try {
            if($this->us['quit_jobs']==1){
             throw  new Exception('代管或离职帐号无法提现');
            }
            if (!$myOrderWithdrawal->checkToken($data['verification'], $this->us['user_id'])) {
                throw  new Exception('请勿重复提交');
            }
            $order_nos = 'shopowner' . order_sn();
            $moeny     = 0;
            $myOrderWithdrawal->startTrans();
            if (!empty($data['id'])) {
                $id = explode(',', $data['id']);
                foreach ($id as $item) {
                    $start  = $myOrderWithdrawal->where('id', $item)->field('start,amount')->find();
                    if($start['start'] ==1){
                        $moeny+=$start['amount'];
                        $myOrderWithdrawal->where('id', $item)->update(['uptme' => time(), 'order_nos' => $order_nos, 'start' => 2]);
                    }


                }

            }
            if ($moeny > 0) {
                $appid        = 'wx454f496af30ccf23';
                $openid       = $data['openid'];//用户标识
                $mch_id       = '1524368381';//商户号
                $key          = 'yiniao20190125102349567745433212';//
                $out_trade_no = $order_nos;//订单号
                $desc         = '零钱提现';//企业付款备注
                $total_fee    = floatval(round($moeny, 2) * 100);//金额
                $name         = $this->us['username'];//收款用户姓名
                require ROOT_PATH . 'extend/weixin/WeixinTi.php'; //引入微信支付
                $weixinpay            = new \WeixinTi($appid, $openid, $mch_id, $key, $out_trade_no, $desc, $total_fee, $name);//配置参数
                $return               = $weixinpay->pay();
                $return               = $this->xmlToArray($return);
                $return['examine_id'] = $data['id'];
                db('log', config('database.zong'))->insert(['type' => 21, 'msg' =>"店长提现", 'admin_id'=>$this->us['user_id'],'content' => json_encode($return), 'created_at' => time()]);
                journal(['url' => $order_nos, 'data' => $return], 1);
                if ($return['return_code'] == 'SUCCESS' && $return['result_code'] == "SUCCESS") {
                    $myOrderWithdrawal->commit();
                    r_date(null, 200);
                } else {
                       $msg= isset($return['err_code_des'])?$return['err_code_des']:$return['return_msg'];
                    throw  new Exception($msg);
                }
            } else {
                throw  new Exception('金额错误');
            }
        } catch (\Exception $e) {
            $myOrderWithdrawal->rollback();
            db('log', config('database.zong'))->insert(['type' => 21, 'admin_id'=>$this->us['user_id'],'msg' => $e->getMessage().$data['id'], 'content' => '店长APP提现', 'created_at' => time()]);
            // 这是进行验证异常捕获
            r_date(null, 300, $e->getMessage());
        }
    }

    /*
     * 提现店长
     */
    public function launch()
    {
        $_POST = Authority::param(['code', 'id', 'verification']);
        if (empty($this->us['openid'])) {
            $code   = $_POST['code'];//获取code
            $appid  = 'wx454f496af30ccf23';
            $secret = '3d6669dc1e161c3b8ac2f6e8067ccb93';
//            $url    = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
            //通过code换取网页授权access_token
            $weixin     = file_get_contents($url);
            $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
            $array      = get_object_vars($jsondecode);//转换成数组
            if(!isset($array['openid'])){
                r_date([], 300, '获取openid失败');
            }
            if($this->us['ce']==2){
                r_date([], 300, '测试帐号禁止提现');
            }
            $openid     = $array['openid'];
            db('user')->where('user_id', $this->us['user_id'])->update(['openid' => $openid]);
        } else {
            $openid = $this->us['openid'];
        }
        $_POST['openid'] = $openid;
        $this->ding($_POST);
    }
    /*
       * 将xml格式转换成数组
       */
    private function xmlToArray($xml)
    {

        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);

        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

        $val = json_decode(json_encode($xmlstring), true);

        return $val;
    }

    /*
     * 已推荐列表
     */

    public function OrderList(OrderModel $orderModel)
    {

        $data            = Authority::param(['stareTime']);
        $data['user_id'] = $this->us['user_id'];
        $list            = $orderModel->MyBonus($data);
        r_date($list, 200);
    }
    /*
     * 推荐详情
     */
    public function RewardInfo(OrderModel $orderModel){
        $data            = Authority::param(['orderId']);
        $list            = $orderModel->RewardDetails($data['orderId']);
        r_date($list, 200);
    }


}